<?php





namespace app\crm\model;



use think\facade\Db;

use app\admin\model\Common;
use app\admin\model\ShopModel;

class ReturnVist extends Common

{



    /**

     * 为了数据库的整洁，同时又不影响Model和Controller的名称

     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀

     */

    protected $name = 'return_vist';



    /**

     * 列表

     * @param  array $request 请求参数

     * @return array

     */

    public function getDataList(array $request): array

    {

        // try {

            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

            // $name       = isset($request['name']) && trim($request['name']) ? trim($request['name']) : '';

            // $categoryId = isset($request['category_id']) && intval($request['category_id']) ? intval($request['category_id']) : 0;

            $where      = [];

            $customer_id = $request['customer_id'] ??0;

            $make_id = $request['make_id'] ??0;

            $shop_id = $request['shop_id'] ??0;

            $customer_name_or_phone = $request['customer_name_or_phone'] ??'';

            $return_visit_time      = $request['return_visit_time'] ??'';

            if ($customer_id > 0) {

                // code...

                array_push($where,['a.customer_id','=',$customer_id]);

            }

            if ($customer_id > 0) {

                // code...

                array_push($where,['a.customer_id','=',$customer_id]);

            }

            $userIds = array();

            if ($make_id > 0) {

                // code...

                 $shopIds = Db::name('shop')->where('make_id', '=', $make_id)->column('shop_id');

                 $userIds = Db::name('customer')->where('id', 'in', $shopIds)->column('id');

            }

            if ($shop_id > 0) {

                // code...

                 $shopIds = Db::name('shop')->where('shop_id', '=', $shop_id)->column('shop_id');

                 $userIds2 = Db::name('customer')->where('id', 'in', $shopIds)->column('id');

                 if($userIds2){

                     $userIds = array_merge($userIds,$userIds2);

                 }else{

                     $userIds = $userIds2 ?? array();

                 }

            }
            
            if ($userIds){

                array_push($where,['a.customer_id','in',$userIds]);

            }

             $export = $request['export'] ?? 0;

            if ($export == 1){

                $ids = $request['id'] ?? [];

                array_push($where,['a.id','in',$ids]);

            }

            

            //客户名字

            if($customer_name_or_phone){

                $shopIds = Db::name('customer')

                ->when(!empty($customer_name_or_phone), function ($query) use ($customer_name_or_phone) {

                        $query->whereOr([['customer_name','like','%'.$customer_name_or_phone.'%'],['telephone','like','%'.$customer_name_or_phone.'%']]);

                    })

                ->column('id');

                array_push($where,['a.customer_id','in',$userIds]);

            }

            

            //时间搜索

            if($return_visit_time){

                $return_visit_time = date('Y-m-d',strtotime($return_visit_time));

                array_push($where,['a.return_visit_time','>=',strtotime($return_visit_time.' 00:00:00')]);

                array_push($where,['a.return_visit_time','<=',strtotime($return_visit_time.' 23:59:59')]);

            }

            $shopIds = $request['shopIds'] ?? [];

            if($shopIds){

                array_push($where,['b.shop_id','in',$shopIds]);

                $dataCount = Db::name('return_vist')->alias('a')
                    ->join('customer b','b.id = a.customer_id','LEFT')
                    ->where($where)->count();
                

            }else{
                $dataCount = Db::name('return_vist')->alias('a')->where($where)->count();
            }

            if ($dataCount) {

                $field = ['a.id','a.customer_id', 'a.create_time', 'a.return_visitor', 'a.return_visit_time', 'a.return_visit_content','a.next_call_back'];

                $list  = $this->alias('a')->join('customer b','b.id = a.customer_id','LEFT')
                
                    ->where($where)->field($field)->order('id DESC')

                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                    ->select()->toArray();

                $userIdArr = array_unique(array_column($list, 'return_visitor'));

                $userList  = Db::name('admin_user')->where('id', 'in', $userIdArr)->column(['realname'], 'id');

                $customerIdArr = array_unique(array_column($list, 'customer_id'));

                $customerList  = Db::name('customer')->where('id', 'in', $customerIdArr)->column(['customer_name,telephone','shop_id'], 'id');

                $shopIdArr = array_unique(array_column($customerList, 'shop_id'));

                

                $shopList  = Db::name('shop')->where('shop_id', 'in', $shopIdArr)->column(['shop_name'], 'shop_id');

                foreach ($list as $key => $val) {

                    $list[$key]['return_visitor_name'] = $userList[$val['return_visitor']] ?? '';

                    $list[$key]['customer_name']       = $customerList[$val['customer_id']]['customer_name'] ?? '';

                    $list[$key]['telephone']       = $customerList[$val['customer_id']]['telephone'] ?? '';

                    $list[$key]['shop_name']       = $shopList[$customerList[$val['customer_id']]['shop_id']] ?? '';

                    $list[$key]['return_visit_time']   = $val['return_visit_time'] > 0 ? date('Y-m-d H:i:s',$val['return_visit_time']) : '';

                    $list[$key]['next_call_back'] = $val['next_call_back'] > 0 ? date('Y-m-d',$val['next_call_back']) : '';

                }

            }

            // echo "<pre>";
            // print_r($list);
            // echo "</pre>";
            // exit;

            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return $data;

        // } catch (\Exception $e) {

        // }



        $this->error = '暂无此数据';

        return [];

    }

    /**

     * 列表

     * @param  array $request 请求参数

     * @return array

     */

    public function addData(array $request): array

    {
        // echo "<pre>";
        // print_r($request);
        // exit;
        Db::startTrans();

        try {

            $nextTime = strtotime($request['next_time']) ?? 0;

            $vistId = $request['vistId'] ?? '';

            $staffInfo = Db::name('admin_user')->where('id',$request['user_id'])->find();

            // echo "<pre>";
            // print_r($staffInfo);

            

            // exit;

            if($vistId){

                $addData['return_visit_time'] = time();

                $addData['return_visit_content']= $request['return_visit_content'] ?? '';

                $addData['return_visitor']      = $request['user_id'] ?? 0;
                
            }else{

                $addData['customer_id']         = $request['customer_id'] ?? 0;

                $addData['return_visit_time']   = time();

                $addData['return_visit_content']= $request['return_visit_content'] ?? '';

                $addData['return_visitor']      = $request['user_id'] ?? 0;

                $addData['create_time']         = time();

                if ($addData['customer_id'] == 0) {

                    // code...

                    $this->error = '请选择回访的客户';

                    return [];

                }
                
            }

            if (empty($addData['return_visit_time'])) {

                // code...

                $this->error = '请选择回访的时间';

                return [];

            }

            if (empty($addData['return_visit_content'])) {

                // code...

                $this->error = '请录入回访的内容';

                return [];

            }

            

            if(!empty($staffInfo['shop_person_id'])){
                // echo "222";
                $save = [

                    'last_kftime'    => time(),

                    'shop_next_time' => $nextTime

                ];

                if($nextTime>0){

                    // echo "111";

                    $next = [

                        'customer_id' => $request['customer_id'] ?? 0,

                        'next_call_back' => $nextTime,

                        'create_time' => time(),

                        'next_type' => 'shop',

                    ];

                }
                

            }else{
                // echo "333";

                $save = [

                    'last_kftime'  => time(),

                    'kf_next_time' => $nextTime

                ];

                $next = [];
            }

            // exit;
            // echo "<pre>";
            // print_r($next);
            // exit;
            // $addData['return_visit_time'] = strtotime($addData['return_visit_time']);

            // $save = [

            //         'last_kftime' => time()

            //     ];

            $customer_id = $request['customer_id'] ?? 0;

            Db::name('customer') -> where('id','=',$customer_id)->save($save);

            if($vistId){

                $id = $this->where('id','=',$vistId)->update($addData);
                
            }else{

                $id = $this->insertGetId($addData);

            }
            // var_dump($id);
            // exit;

            if(!empty($next)){

                $nextId = Db::name('return_vist')->insertGetId($next);

            }

            Db::commit();

            return ['id'=>$id];

        } catch (\Exception $e) {

            Db::rollback(); // 回滚

            $this->error = '添加失败';

            return [];

        }



        // $this->error = '添加成功';

        // return [];

    }

    

    ///// 定时回访记录 /////

    public function getList(array $request): array

    {

        // echo "<pre>";
        // print_r($request);
        // exit;

        $is_vist = $request['is_vist'] ?? '1';

        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 10;

        $stime = strtotime('-1 days');

        // $etime = strtotime('+7 days');

        $startTime = $request['yjreturn_visit_time'] ?? '';

        $endTime = $request['yjreturn_visit_time2'] ?? '';

        // echo "时间：".$startTime.'-'.$endTime;

        $start_time = strtotime($startTime.'00:00:00');

        
        $end_time = $endTime>0 ? strtotime($endTime.'23:59:59') : '';
        
        

            

        $userInfo = $request['userInfo']??[];

        if ($userInfo == []){

            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return $data;

        }

        $where = [];

        if($is_vist == '1'){
            array_push($where,['r.return_visit_time','=','0']);
        }else{
            array_push($where,['r.return_visit_time','>','0']);
        }

        if($request['shopIds']){
            array_push($where,['c.shop_id','in',$request['shopIds']]);
        }

        $shop_person_id = $userInfo['shop_person_id'] ?? '';
        $groupId = $userInfo['group_id'] ?? '';

        

        if(empty($shop_person_id)){
            if($start_time){
                array_push($where,['c.kf_next_time','>',"$start_time"]);
            }
            
            if($end_time){
                array_push($where,['c.kf_next_time','<',"$end_time"]);
            }
            
            if($groupId == 50){
                array_push($where,['c.operator','=',$userInfo['id']]);
                // echo "客服";
            }else{
                // echo "非客服";
            }
            
        }else{

            if($start_time){
                array_push($where,['c.shop_next_time','>',"$start_time"]);
            }

            if($end_time){
                array_push($where,['c.shop_next_time','<',"$end_time"]);
            }
            // echo "门店员工";

        }

        

        $dataCounts = Db::name('return_vist')->alias('r')
            ->join('customer c','c.id = r.customer_id','LEFT')
            ->where($where)->count();
            // echo "<pre>";
            // print_r($dataCounts);
            // echo "</pre>";exit;
        if($dataCounts){
            $filed = ['c.id', 'c.customer_name', 'c.sex','c.telephone', 'c.birthday', 'c.effective_entry', 'c.shop_id','c.source_id','c.effective_entry','c.status','c.create_time','c.first_time','c.second_time','c.member_classification','c.turn_status','c.age','c.membership_leve','c.nurse_id','c.repair_progress','c.consumption','c.new_join_shop_time','c.final_consumption','c.final_service','c.be_overdue_time','c.cj_time','c.cj_money','c.operator','c.last_kftime','c.difficulty_level','c.kf_next_time','c.shop_next_time'];
            $list = Db::name('return_vist')->alias('r')
                            ->join('customer c','c.id = r.customer_id','LEFT')
                            ->where($where)
                            ->field($filed)
                            ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                            ->select()->toArray();
    
            // echo "<pre>";
            // print_r($list);

            $shopIds        = array_values(array_unique(array_column($list, 'shop_id')));
            $nurseIds       = array_values(array_unique(array_column($list, 'nurse_id')));
            $operatorIds    = array_values(array_unique(array_column($list, 'operator')));

            //获取店铺数据
            $shopList       = Db::name('shop')->where('shop_id', 'in', $shopIds)->column('shop_name,market_name', 'shop_id');
            //获取员工数据
            $personList     = Db::name('shop_person')->where('id', 'in', $nurseIds)->column('name', 'id');
            //获取会员等级
            $gradeList      = Db::name('customer_grade')->column('name', 'id');
            $adminList      = Db::name('admin_user')->where('id', 'in', $operatorIds)->column('realname', 'id');
            //基础配置
            $settingList    = Db::name('setting')->column('name', 'id');
            $sexArr         = ['0' => '未知', '1' => '男', '2' => '女'];
            $EntryArr       = ['1' => '是', '2' => '否'];

            foreach($list as $key => $val){
                if ($val['birthday']) {
                    $setData            = array();
                    $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']),0);
                    $setData['id']      = $val['id'];
                    $saveAll[]          = $setData;
                    $list[$key]['age']  = $setData['age'];
                }
            }

            foreach ($list as $key => $val) {
                $list[$key]['sex']             = $sexArr[$val['sex']] ?? '未知';
                $list[$key]['effective_entry'] = $EntryArr[$val['effective_entry']] ?? '否';
                $list[$key]['shop_name']       = $shopList[$val['shop_id']]['shop_name'] ?? '';
                // $list[$key]['market_name']       = $shopList[$val['shop_id']]['market_name'] ?? '';
                // $list[$key]['birthday']        = $val['birthday'] ? date('Y-m-d', $val['birthday']) : '';
                $list[$key]['source_name']     = $settingList[$val['source_id']] ?? '';
               
                // 负责人名称
                $list[$key]['nurse_name']      = $personList[$val['nurse_id']] ?? '';

                // 客服名称
                $list[$key]['operator']      = $adminList[$val['operator']] ?? '';

                if(empty($shop_person_id)){
                    $list[$key]['next_visit_time'] = $val['kf_next_time'] > 0 ? date('Y-m-d',$val['kf_next_time']) : '';
                }else{
                    $list[$key]['next_visit_time'] = $val['shop_next_time'] > 0 ? date('Y-m-d',$val['kf_next_time']) : '';
                }
                
                // 客户的名称
                $list[$key]['customer_service_name'] = $adminList[$val['operator']] ?? '';
                $list[$key]['customer_name_phone'] = $val['customer_name'].'/'.$val['telephone'];
            }
        }

        // echo "<pre>";
        // print_r($list);

        $data              = [];

        $data['list']      = $list ?? [];

        $data['dataCount'] = $dataCounts ?? 0;

        return $data;

        
    }

    

    public function addDs(array $request): array

    {

        

        try {

            $addData['shop_id']     = $request['shop_id'] ?? 0;

            $addData['customer_id'] = $request['customer_id'] ?? 0;

            $addData['user_id']     = $request['user_id'] ?? 0;

            $addData['create_time'] = time();

            $addData['yjreturn_visit_time']     = isset($request['yjreturn_visit_time']) ? strtotime($request['yjreturn_visit_time']) : '';

            $addData['yjreturn_visit_content']  = $request['yjreturn_visit_content'] ?? '';

            

            if ($addData['shop_id'] == 0 || $addData['customer_id'] == 0){

                $this->error = '请选择预约回访的客户';

                return [];

            }

            

            if (empty($addData['yjreturn_visit_time'])){

                $this->error = '请选择预约回访的时间';

                return [];

            }

            

            if (empty($addData['yjreturn_visit_content'])){

                $this->error = '请填写预约回访的内容';

                return [];

            }

            $id = Db::name('return_vist_ds')->insertGetId($addData);

            $this->error = '预约回访提交成功';

            return ['id'=>$id??0];

        } catch (\Exception $e) {

            $this->error = '预约回访提交成功失败';

            return [];

        }

    }

     public function addDsXh(array $request): array

    {

        

        try {

            $id      = $request['id'] ?? 0;

            $user_id = $request['user_id'] ?? 0;

            $saveData['return_visit_time']    = time();

            $saveData['return_visit_content'] = $request['return_visit_content'] ?? '';

            

            $find = Db::name('return_vist_ds')->where('id','=',$id)->find();

            if(!$find){

                $this->error = '预约回访记录不存在';

                return [];

            }

            if ($find['return_visit_time'] > 0) {

                $this->error = '预约回访已被处理';

                return [];

            }

            if(empty($saveData['return_visit_content'])){

                $this->error = '预约回访记录不能为空';

                return [];

            }

            if ($find['user_id'] != $user_id) {

                $this->error = '请处理属于自己的预约回访';

                return [];

            }

            Db::name('return_vist_ds')->where('id','=',$id)->update($saveData);

            $this->error = '预约回访处理成功';

            return ['id'=>$id??0];

        } catch (\Exception $e) {

            $this->error = '预约回访处理失败';

            return [];

        }

    }


    /**

     * 修复方案列表

     * @param  array $request 请求参数

     * @return array

     */

    public function getRepairPlanList(array $request): array

    {
        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $customer_id = $request['customer_id'];

        $where = [];

        array_push($where,['customer_id','=',$customer_id]);

        $field = ['id','customer_id', 'create_time', 'repair_visitor', 'repair_plan_time', 'repair_plan_content'];

        $list  = Db::name('repair_plan')->where($where)->field($field)->order('id DESC')->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->select()->toArray();

        $userIdArr = array_unique(array_column($list, 'repair_visitor'));

        $userList  = Db::name('admin_user')->where('id', 'in', $userIdArr)->column(['realname'], 'id');

        $customerIdArr = array_unique(array_column($list, 'customer_id'));

        $customerList  = Db::name('customer')->where('id', 'in', $customerIdArr)->column(['customer_name,telephone','shop_id'], 'id');

        $shopIdArr = array_unique(array_column($customerList, 'shop_id'));

        $shopList  = Db::name('shop')->where('shop_id', 'in', $shopIdArr)->column(['shop_name'], 'shop_id');

        foreach ($list as $key => $val) {

            $list[$key]['repair_visitor_name'] = $userList[$val['repair_visitor']] ?? '';

            $list[$key]['customer_name']       = $customerList[$val['customer_id']]['customer_name'] ?? '';

            $list[$key]['telephone']       = $customerList[$val['customer_id']]['telephone'] ?? '';

            $list[$key]['shop_name']       = $shopList[$customerList[$val['customer_id']]['shop_id']] ?? '';

            $list[$key]['repair_plan_time']   = date('Y-m-d H:i:s',$val['repair_plan_time']);

        }


        $data              = [];

        $data['list']      = $list ?? [];

        $data['dataCount'] = count($list) ?? 0;

        return $data;

        
    }


    /**

     * 添加修护方案

     * @param  array $request 请求参数

     * @return array

     */

    public function addRepairData(array $request): array

    {

        try {

            $addData['customer_id']         = $request['customer_id'] ?? 0;

            $addData['repair_plan_time']   = time();

            $addData['repair_plan_content']= $request['repair_plan_content'] ?? '';

            $addData['repair_visitor']      = $request['user_id'] ?? 0;

            $addData['create_time']         = time();

            if ($addData['customer_id'] == 0) {

                // code...

                $this->error = '请选择添加方案的客户';

                return [];

            }

            // if (empty($addData['return_visit_time'])) {

            //     // code...

            //     $this->error = '请选择回访的时间';

            //     return [];

            // }

            if (empty($addData['repair_plan_content'])) {

                // code...

                $this->error = '请录入修复方案的内容';

                return [];

            }


            $save = [

                    'last_kftime' => time()

                ];

            Db::name('customer') -> where('id','=',$addData['customer_id'])->save($save);

            // $id = $this->insertGetId($addData);

            $id = Db::name('repair_plan')->insertGetId($addData);

            return ['id'=>$id];

        } catch (\Exception $e) {

            $this->error = '添加失败';

            return [];

        }

    }
    /*模型关联 shop表 */
    public function shop(){

        return $this->hasOne(ShopModel::class);

    }

}

